/**
 * Copyright (c) 2012 Nokia Corporation.
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

import QtQuick 1.1
import com.nokia.symbian 1.1
import com.nokia.extras 1.1
import QtMobility.location 1.2
import SocialConnectPlugin 1.0
import "CommonFunctions.js" as Functions

PageStackWindow {
    id: main
    property bool listViewVisible: false
    property Coordinate lastUpdatePos: Coordinate {}
    property alias map: placesMapPage.placesMap

    signal readyToBeShown()

    showStatusBar: true
    showToolBar: true
    initialPage: PlacesMapPage { id: placesMapPage; tools: mainToolBarLayout }

    Connections {
        target: placesListModel
        onError: Functions.requestFailed(requestId, errorString);
    }

    Connections {
        target: routeManager
        onRequestFailed: Functions.requestFailed(error);
    }

    /*!
      Process logout completed.
     */
    function logoutCompleted() {
        Qt.quit();
    }

    /*!
      Process login. Enables GPS tracking.
     */
    function loginCompleted() {
        positionSource.active = true;
    }

    // A dialog to be shown if an error occurs.
    QueryDialog {
        id: errorDialog
        titleText: qsTr("Error");
        acceptButtonText: qsTr("Ok");
    }

    StatusBar {
        id: statusBar
        z: 1
        anchors.top: parent.top
    }

    Text {
        z: 2

        anchors {
            left: parent.left
            leftMargin: platformStyle.paddingSmall
        }

        font {
            family: platformStyle.fontFamilyRegular
            pixelSize: platformStyle.fontSizeMedium
        }

        color: platformStyle.colorNormalLight
        text: "Places Around"
    }

    // Construct the Facebook Connect plug-in instance.
    FacebookConnect {
        id: fbConnect

        appId: "258008130941043"
        appName: "PlacesAround"
        organization: "Nokia"

        Component.onCompleted: {
            logoutCompleted.connect(main.logoutCompleted);
            accessTokenChanged.connect(main.loginCompleted);
            requestCompleted.connect(Functions.requestCompleted)
            requestFailed.connect(Functions.requestFailed);
            permissions = ["publish_stream"];

            if (!isAuthorized()) {
                console.debug("Not authorized!");
                initTimer.start();
            }
            else {
                console.debug("Already authorized.");
                loginCompleted();
                initTimer.openLoginPage = false;
                initTimer.start();
            }
        }
    }

    // Timer for emitting readyToBeShown() signal and pushing the login page to
    // the page stack if necessary. The latter ensures that the login page is
    // pushed on top of the map page.
    Timer {
        id: initTimer
        property bool openLoginPage: true
        interval: 1000
        repeat: false
        running: false

        onTriggered: {
            if (openLoginPage) {
                console.debug("Opening the login page.")
                pageStack.push("qrc:/LoginPage.qml");
            }

            main.readyToBeShown();
        }
    }

    PositionSource {
        id: positionSource
        updateInterval: 5000
        active: false
        property bool initialized: false

        onPositionChanged: {
            if (!initialized) {
                Functions.checkForUpdate(true);
                map.updateCoordinates(position.coordinate);
                map.positionSourceInitialized();
                initialized = true;
            }
            else {
                map.moveHereToCoordinate(position.coordinate, 300);
            }

            Functions.checkForUpdate(false);
            settings.setSetting("last_latitude", position.coordinate.latitude);
            settings.setSetting("last_longitude", position.coordinate.longitude);
        }
    }

    // Bar containing a text filter for entering text for filtering the found
    // places.
    FilterBar {
        id: filterBar
        anchors.top: statusBar.bottom
    }

    // When exiting show this dialog and let the user select whether to logout
    // from Facebook before or leave the session open.
    QueryDialog {
        id: logoutDialog
        height: 200
        titleText: qsTr("Confirmation");
        message: qsTr("Logout from Facebook before exiting?");
        acceptButtonText: qsTr("Yes");
        rejectButtonText: qsTr("No");
        onAccepted: fbConnect.logout();
        onRejected: Qt.quit();
    }

    ToolBarLayout {
        id: mainToolBarLayout

        ToolButton {
            flat: true
            iconSource: "toolbar-back"
            onClicked: logoutDialog.open();
        }

        ButtonRow {
            id: buttonRow
            property bool mapSelected: true
            checkedButton: mapViewButton

            ToolButton {
                id: mapViewButton
                checked: buttonRow.mapSelected
                iconSource: "qrc:/map-icon.png"
                onClicked: {
                    if (!buttonRow.mapSelected) {
                        Functions.showMap();
                    }
                }
            }
            ToolButton {
                id: listViewButton
                iconSource: "toolbar-list"
                onClicked: {
                    if (buttonRow.mapSelected) {
                        pageStack.push("qrc:///PlacesListPage.qml", { tools: mainToolBarLayout });
                        buttonRow.mapSelected = false;
                        listViewVisible = true;
                    }
                }
            }
        }

        ToolButton {
            id: searchButton
            flat: true
            iconSource: "toolbar-search"
            onCheckedChanged: checked ? filterBar.state = "shown"
                                      : filterBar.state = "hidden";
            checkable: true
        }
    }
}
